<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Jobs\Bookjob;
use App\Jobs\BookSortJob;
use App\Jobs\SortJob;
use App\Models\Book;
use App\Models\BookCate;
use App\Models\BookInfo;
use App\Models\BookUpload;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use function App\Helpers\createdGuid;
use function App\Helpers\createTableChapter;
use function App\Helpers\createTableContent;
use function App\Helpers\errorMsg;
use function App\Helpers\successMsg;

class BookController extends Controller
{
    const PER_PAGE = 15;//分页常量
    //获取书籍列表
    public function bookList(Request $request)
    {
        $page = $request->page ?? 1;
        $per_page = $request->per_page ?? self::PER_PAGE;
        $whereSearch = Book::executeSearch($request);
        $data = Book::query()->with("info")->where($whereSearch)->limit($per_page)->offset(($page-1)*$per_page)->get();
        $total = Book::query()->where($whereSearch)->count("id");
        $data = [
            'data' => $data,
            'total' => $total,
            'page' => $page,
            'per_page' => $per_page
        ];
        return successMsg($data);
    }
    //添加书籍
    public function bookInsert(Request $request)
    {
        $data = Book::executeInsert($request);
        $data['uni_code'] = createdGuid("book");
        $data['year'] = date("Y");
        $data['month'] = date("m");
        $data['created_at'] = date("Y-m-d H:i:s",time());
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        DB::beginTransaction();
        try {
            $book_id = Book::query()->insertGetId($data);
            $row = BookInfo::query()->insert(['book_id' => $book_id]);
            if(!$book_id || !$row){
                DB::rollBack();
                return errorMsg(-1,"数据插入失败!!");
            }else{
                DB::commit();
                return successMsg();
            }
        }catch (\Exception $e){
            DB::rollBack();
            return errorMsg(-1,"数据插入失败!!");
        }
    }
    //更新书籍
    public function bookUpdate(Request $request)
    {
        $book_uni_code = $request->book_uni_code ?? null;
        $data = Book::executeUpdate($request);
        $data=array_filter($data,function ($v){
            return !is_null($v);
        },ARRAY_FILTER_USE_BOTH);
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        if(is_null($book_uni_code)) return errorMsg(-1,"必填字段不能为空!!!");//数据更新失败!!!
        Book::query()->where("uni_code",$book_uni_code)->update($data);
        return successMsg();
    }
    //删除书籍
    public function bookDelete(Request $request)
    {
        $book_uni_codes = $request->book_uni_codes ?? null;
        $book_uni_code_arr = is_array($book_uni_codes) ? $book_uni_codes : explode(',',$book_uni_codes) ;
//        $book_ids = Book::query()->whereIn('uni_code',$book_uni_code_arr)->get('id')->toArray();
//        $book_arr_id = array_column($book_ids,"id");
//        BookInfo::query()->whereIn('book_id',$book_arr_id)->delete();
        Book::query()->whereIn('uni_code',$book_uni_code_arr)->update(['is_del' => 1]);
        return successMsg();
    }
    //获取书籍类别列表
    public function bookCateList()
    {
        $data = BookCate::getBookCateByPid(0);
        return successMsg($data);
    }
    //书籍章节内容上传
    public function BookChapterContentUpload(Request $request)
    {
        $book_uni_code = $request->book_uni_code ?? null;
        $path = $request->path ?? null;
        $book = Book::query()->where('uni_code','=',$book_uni_code)->first();
        $year = $book->year;
        if(!Schema::hasTable(Config::get("site.chapter_table").$year)){
            $row = createTableChapter($year);
            if(!$row) return errorMsg(-1,'章节数据表创建失败!!!');
        }
        if(!Schema::hasTable(Config::get("site.content_table").$year)){
            $row = createTableContent($year);
            if(!$row) return errorMsg(-1,'内容数据表创建失败!!!');
        }
        $book_upload = BookUpload::query()->where("book_id",$book->id)->first();
        if($book_upload) return errorMsg(-1,"该书籍已经有文件上传!!!");
        //添加到book_upload表
        $book_upload_data = [
            'path' => $path,
            'book_id' => $book->id,
            'created_at' => date("Y-m-d H:i:s",time()),
        ];
        BookUpload::query()->insert($book_upload_data);
        Bookjob::dispatch($path,$year,$book->id,$book_uni_code);
        return successMsg();
    }
    //书籍一键排序
    public function bookFastSort(Request $request)
    {
        $book_uni_code = $request->book_uni_code ?? null;
        $book = DB::table("book")->where('uni_code',$book_uni_code)->first();
        $chapter_table =  Config::get("site.chapter_table").$book->year;
//        return $chapter_table;
        BookSortJob::dispatch($chapter_table,$book->id);
        return successMsg();
    }
    //计算一本书的字数
    public function bookWordTotal(Request $request)
    {
        $book_uni_code = $request->book_uni_code ?? null;
        $year = Book::query()->where('uni_code',$book_uni_code)->value("year");
        $chapter_table =  Config::get("site.chapter_table").$year;
        $chapter_word = DB::table($chapter_table)->where("book_uni_code",$book_uni_code)->sum("word");
        Book::query()->where('uni_code',$book_uni_code)->update(['word' => $chapter_word]);
        return successMsg();
    }

}
